import React, {Component} from 'react';

import {
    DeviceEventEmitter,
    FlatList,
    Image,
    LayoutAnimation,
    ListView,
    Platform,
    StyleSheet,
    Text,
    TextInput,
    TouchableOpacity,
    UIManager,
    View
} from 'react-native';
import StyleUtils from "../../../res/styles/StyleUtils";
import Navigation from "../../../custom/Navigation";
import IparImageView from "../../../custom/IparImageView";
import CheckBox from "react-native-check-box";
import ViewUtils from "../../../utils/ViewUtils";
import ModalBottomUtils from "../../../utils/ModalBottomUtils";
import IparInput from "../../../custom/IparInput";
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import CommonUtils from "../../../common/CommonUtils";
import I18n from "../../../res/language/i18n";
import {KeyboardAwareScrollView} from "react-native-keyboard-aware-scroll-view";
import ReturnOrdersPage from "./ReturnOrdersPage";
import ImagePicker from 'react-native-image-picker';


const ds = new ListView.DataSource({
    rowHasChanged: (row1, row2) => row1 !== row2,
});
const photoOptions = {
    //底部弹出框选项
    title: I18n.t('default.selectCamera'),
    cancelButtonTitle: I18n.t('default.cancel'),
    takePhotoButtonTitle: I18n.t('default.camera'),
    chooseFromLibraryButtonTitle: I18n.t('default.photo'),
    quality: 0.72,
    allowsEditing: true,
    maxWidth: 500,
    noData: false,
    storageOptions: {
        skipBackup: true,
        path: 'images'
    }
};
export default class ReturnGoodsPage extends Component {

    constructor(props) {
        super(props);

        this.iparNetwork = new IparNetwork();

        let goodsData = (this.props.orderData && this.props.orderData.goods) || [];
        for (dataItem of goodsData) {
            dataItem.isChecked = true;
        }
        this.descText = '';
        this.state = {
            viewTypeIsSelectGoods: true,
            goodsData: goodsData,

            userGoodsImage: null,

            orderRefundAmount: 0.0,

            selectGoodsData: goodsData,

            selectReturnType: null,
            selectReturnReason: null,
            returnReasonData: [],

            modalVisible: false,
            modalType: null,//0 returnType / 1 Return reason
        };
    }


    /**
     * 0 正常  1 换货  2 退货退款 3 退款
     * @type {*[]}
     */
    returnTypeData(orderStatus) {
        if (orderStatus < 12) {
            return [{key_name: I18n.t('RT.refund'), code: 3},]
        }
        return [
            // {key_name: I18n.t('RT.exchangeGoods'), code: 1},
            {key_name: I18n.t('RT.exchangeRefund'), code: 2},
        ]
    };

    componentDidMount() {
        CommonUtils.getAcyncInfo('userInfo')
            .then((result) => {
                this.userData = JSON.parse(result);
            })
    }

    /**
     * 获取退货原因
     */
    getReasonData(returnType) {
        CommonUtils.showLoading();

        this.iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'getReturnReason?',
            'reason_type=' + returnType)
            .then((result) => {
                CommonUtils.dismissLoading();
                if (result.code === 200) {
                    this.setState({
                        returnReasonData: result.data || []
                    });
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }
            })
            .catch((error) => {
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('ReturnGoodsPage---getReasonData--error:' + error);
                CommonUtils.dismissLoading();
            });
    }


    /**
     * goods item
     * @param item
     * @param index
     * @returns {*}
     */
    renderItem(item, index) {
        let state = this.state;


        let showIcon = item.isChecked;

        if (state.viewTypeIsSelectGoods) {
            showIcon = true;
        }

        return <TouchableOpacity
            key={index}
            onPress={() => !state.viewTypeIsSelectGoods && this.updateGoodsSelectViewType(true)}
            style={[StyleUtils.rowDirection,
                state.viewTypeIsSelectGoods && {
                    alignItems: 'center',
                    paddingTop: 8,
                    paddingBottom: 8,
                    borderBottomWidth: 0.2
                }]}>

            {state.viewTypeIsSelectGoods && <CheckBox
                style={{marginRight: 8}}
                onClick={() => {
                    let _goodsData = state.goodsData;
                    _goodsData[index].isChecked = !_goodsData[index].isChecked;
                    this.setState({
                        goodsData: _goodsData,
                    });
                }}
                isChecked={item.isChecked}/>}

            <IparImageView
                url={item.image}
                width={showIcon ? 80 : 0}
                height={showIcon ? 80 : 0}
            />

            {state.viewTypeIsSelectGoods &&
            <View style={[{height: 80, justifyContent: 'space-between', padding: 8, flex: 1}]}>
                <Text
                    numberOfLines={2}
                    style={[StyleUtils.smallFont]}>{item.goods_name}</Text>

                <View style={[StyleUtils.rowDirection, {
                    width: 98,
                    alignItems: 'center',
                    borderWidth: 1,
                    borderColor: '#cbcbcb'
                }]}>
                    <TouchableOpacity
                        onPress={() => this.editGoodsNum(false, item, index)}
                        style={[styles.iconBox, StyleUtils.center]}>
                        <Image
                            style={[styles.iconSize]}
                            source={require('../../../res/images/ic_reduce.png')}/>
                    </TouchableOpacity>

                    <Text style={[{
                        paddingLeft: 8,
                        paddingRight: 8,
                        width: 40,
                        textAlign: 'center'
                    }]}>{item.edit_goods_number || item.goods_number}</Text>
                    <TouchableOpacity
                        onPress={() => this.editGoodsNum(true, item, index)}
                        style={[styles.iconBox, StyleUtils.center]}>
                        <Image
                            style={[styles.iconSize]}
                            source={require('../../../res/images/ic_add.png')}/>
                    </TouchableOpacity>
                </View>
            </View>}

        </TouchableOpacity>
    };


    /**
     * Size goods edit
     * 修改产品数量
     * @param isAdd => 是否添加
     * @param goods
     * @param index
     */
    editGoodsNum(isAdd, goods, index) {

        let _goodsNumber = goods.edit_goods_number || goods.goods_number;
        if (isAdd) {
            if (goods.goods_number !== _goodsNumber) _goodsNumber++;
        } else if (_goodsNumber !== 1) {
            _goodsNumber--;
        }


        let _goodsData = this.state.goodsData;
        _goodsData[index].edit_goods_number = _goodsNumber;
        this.setState({
            goodsData: _goodsData
        });

    }


    /**
     * 打开相机
     * */
    cameraAction() {
        ImagePicker.showImagePicker(photoOptions, (response) => {
            if (response.didCancel) {
                console.log('User cancelled image picker');
            } else if (response.error) {
                console.log('ImagePicker Error: ', response.error);
            } else {

                CommonUtils.showLoading();
                let formData = new FormData();
                formData.append("prefix", this.props.orderData.order_sn);
                formData.append("file", 'data:image/jpeg;base64,' + response.data);
                formData.append("dir", "order");
                this.iparNetwork.getPostFrom(SERVER_TYPE.imgIpar + 'UploadFile?', formData)
                    .then((result) => {
                        if (result.code === 200 && result.data) {
                            let images = this.state.userGoodsImage;
                            images = images ? images + ',' + result.data.url : result.data.url;
                            this.setState({
                                userGoodsImage: images,
                            });
                            DeviceEventEmitter.emit('toast', I18n.t('default.success'));
                            console.log(result);
                        } else {
                            DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
                        }
                        CommonUtils.dismissLoading();

                    })
                    .catch((error) => {
                        CommonUtils.dismissLoading();
                        console.log(error);
                        DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                    })
            }
        });
    }

    /**
     * updateGoodsSelectViewType
     * @param complete
     */
    updateGoodsSelectViewType(complete) {

        let _selectGoodsData = [];
        let orderRefundAmount = 0.0;
        if (!complete) {
            let isSelected = false;

            for (dataItem of this.state.goodsData) {
                if (dataItem.isChecked) {
                    _selectGoodsData.push(dataItem);
                    orderRefundAmount += (dataItem.shop_pv * (dataItem.edit_goods_number || dataItem.goods_number));
                    isSelected = true;
                }
            }

            if (!isSelected) {
                DeviceEventEmitter.emit('toast', I18n.t('RT.selectGoods'));
                return;
            }

        }
        this.setState({
            viewTypeIsSelectGoods: complete,
            selectGoodsData: _selectGoodsData,
            orderRefundAmount,
        });
        this.startAnimation();
    }

    /**
     * 动画效果
     */
    startAnimation() {
        if (Platform.OS === 'android') {
            UIManager.setLayoutAnimationEnabledExperimental(true);
        }
        LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);

    }

    /**
     * renderSelectGoodsView
     * @returns {*}
     */
    renderSelectGoodsView() {
        let typeIsSelectGoods = this.state.viewTypeIsSelectGoods;

        return <View style={{flex: 1, backgroundColor: 'white'}}>
            {typeIsSelectGoods && <Text
                numberOfLines={1}
                style={[styles.goodsTitle, StyleUtils.smallFont]}>{I18n.t('RT.selectGoods')}</Text>}
            <View
                style={[styles.box, {padding: 16}]}>
                <FlatList
                    extraData={this.state}
                    horizontal={!typeIsSelectGoods}
                    keyExtractor={(item, index) => index}
                    renderItem={(index) => this.renderItem(index.item, index.index)}
                    data={this.state.goodsData}
                />
            </View>


        </View>
    }

    /**
     *
     * @param style
     * @param text
     * @param value
     * @param type
     * @returns {*}
     */
    renderSelectView(style, text, value, type) {
        return <TouchableOpacity
            onPress={() => {
                if (type === 1 && !this.state.selectReturnType) {
                    DeviceEventEmitter.emit('toast', I18n.t('RT.selectReturnType'));
                    type = 0;
                }
                this.setState({
                    modalType: type,
                    modalVisible: true,
                });
            }}
            style={[StyleUtils.justifySpace, {paddingTop: 8, paddingBottom: 8}, style]}>

            <Text style={[StyleUtils.smallFont, styles.text]}>{text}</Text>

            <View
                style={[StyleUtils.rowDirection, {alignItems: 'center',}]}>
                <Text style={[StyleUtils.smallFont, styles.text, {color: 'gray', paddingLeft: 16}]}>{value}</Text>
                <Image
                    style={[styles.iconSize, {tintColor: 'gray', marginLeft: 8}]}
                    source={require('../../../res/images/ic_right_more.png')}/>
            </View>
        </TouchableOpacity>
    }


    /**
     * @returns {*}
     */
    renderReturnGoodsView() {

        let props = this.props;
        let state = this.state;

        return <View style={[{marginTop: 6, flex: 1,}]}>

            <View style={[styles.box, {padding: 16}]}>
                {this.renderSelectView(null, I18n.t('RT.returnType'), state.selectReturnType && state.selectReturnType.key_name, 0)}
                {this.renderSelectView({marginTop: 8}, I18n.t('RT.returnReason'), state.selectReturnReason && I18n.t('RT.' + state.selectReturnReason.key_name), 1)}
            </View>

            <View style={[styles.box, {padding: 16, marginTop: 8,}]}>
                {state.selectReturnType && state.selectReturnType.code !== 1 &&
                <View style={[StyleUtils.rowDirection,]}>
                    <Text style={[styles.text]}>{I18n.t('RT.refundAmount')}</Text>
                    <Text style={[styles.text, {
                        color: "red",
                        paddingLeft: 8
                    }]}>{(state.selectReturnType && state.selectReturnType.code === 3 ? props.orderData.pay_amount : state.orderRefundAmount * props.swap_amount).toFixed(2) + ' ' + props.currencyCode}</Text>
                </View>}
                {/*<View style={[StyleUtils.rowDirection, {marginTop: 8,}]}>*/}
                {/*    <Text style={[styles.text,]}>{I18n.t('default.remarks')}</Text>*/}
                {/*</View>*/}
                <View style={{
                    borderWidth: 1,
                    borderColor: '#f3f3f3',
                    marginTop: 8,
                    padding: 8,
                }}>
                    <TextInput
                        placeholder={I18n.t('default.remarks')}
                        placeholderTextColor={'#BBBBBB'}
                        underlineColorAndroid={'transparent'}
                        onChangeText={(text) => this.descText = text}
                        multiline
                        style={[{
                            paddingVertical: 0,
                            fontSize: 16,
                            height: 80,
                        }]}
                    />
                </View>

            </View>


            <View style={[styles.box, {
                padding: 16,
                paddingTop: 0,
                marginTop: 8,
                flexWrap: 'wrap',
            }, StyleUtils.rowDirection]}>

                {this.state.userGoodsImage && this.state.userGoodsImage.split(',').map((item, index) => {
                    return <TouchableOpacity style={{marginRight: 16, marginTop: 16, height: 60}}>
                        <IparImageView width={60} height={60} url={item}/>
                    </TouchableOpacity>
                })}
                <TouchableOpacity
                    onPress={() => this.cameraAction()}>
                    <Image
                        style={[{width: 60, height: 60, marginRight: 16, marginTop: 16}]}
                        source={require('../../../res/images/ic_add_image.png')}/>
                </TouchableOpacity>
            </View>


        </View>
    }


    render() {
        let orderData = this.props.orderData;
        let state = this.state;
        let typeIsSelectGoods = state.viewTypeIsSelectGoods;


        return (
            <View style={[StyleUtils.flex,
                !typeIsSelectGoods && {
                    backgroundColor: '#f3f3f3'
                }]}>
                <Navigation
                    title={I18n.t('RT.returnGoods')}
                    onClickLeftBtn={() => this.props.navigator.pop()}/>

                <KeyboardAwareScrollView style={{marginBottom: 80}}>
                    {this.renderSelectGoodsView()}
                    {!typeIsSelectGoods && this.renderReturnGoodsView()}
                </KeyboardAwareScrollView>
                <View style={[{
                    padding: 16,
                    paddingTop: 8,
                    position: "absolute",
                    left: 0,
                    right: 0,
                    bottom: 0,
                    backgroundColor: 'rgba(255,255,255,0.9)'
                }]}>
                    {
                        ViewUtils.getButton(I18n.t('default.submit'), () => {
                            if (typeIsSelectGoods) {
                                this.updateGoodsSelectViewType(false);
                            } else {
                                this.submit();
                            }
                        }, {
                            height: 46,
                            marginTop: 20
                        })}
                </View>

                <ModalBottomUtils
                    renderRow={(rowData) => {
                        let selectReturnType = this.state.selectReturnType;
                        let selectReturnReason = this.state.selectReturnReason;

                        if (this.state.modalType === 0) {//return type
                            selectReturnType = rowData;
                        } else {
                            selectReturnReason = rowData;
                        }
                        return <TouchableOpacity
                            onPress={() => {
                                this.setState({
                                    modalVisible: false,
                                    selectReturnReason,
                                    selectReturnType,
                                });

                                if (this.state.modalType === 0) {//return type
                                    this.getReasonData(selectReturnType.code);
                                }
                            }}
                            style={{padding: 8}}>
                            <Text
                                style={[StyleUtils.smallFont, styles.text]}>{this.state.modalType === 0 ? rowData.key_name : I18n.t('RT.' + rowData.key_name)}</Text>
                        </TouchableOpacity>
                    }}
                    visible={state.modalVisible}
                    requestClose={() => {
                        this.setState({
                            modalVisible: false
                        });
                    }}
                    dataSource={ds.cloneWithRows(state.modalType === 0 ? this.returnTypeData(orderData.order_status) : state.returnReasonData)}
                    title={I18n.t(state.modalType === 0 ? 'RT.selectReturnType' : 'RT.selectReturnReason')}/>

            </View>
        );
    }


    /**
     * 提交
     */
    submit() {
        let state = this.state;

        if (!state.selectReturnType) {
            DeviceEventEmitter.emit('toast', I18n.t('RT.selectReturnType'));
            return;
        }

        if (!state.selectReturnReason) {
            DeviceEventEmitter.emit('toast', I18n.t('RT.selectReturnReason'));
            return;
        }

        if (!this.descText || (this.descText && !this.descText.trim())) {
            DeviceEventEmitter.emit('toast', I18n.t('default.remarks'));
            return;
        }

        CommonUtils.showLoading();
        let orderData = this.props.orderData;
        let goodsData = [];
        for (goods of state.selectGoodsData) {
            let _goodsData = {goods_id: goods.goods_id, goods_number: goods.edit_goods_number || goods.goods_number,};
            goodsData.push(_goodsData)
        }
        let data = {
            order_id: orderData.order_id,
            return_type: state.selectReturnType.code,
            return_reason: state.selectReturnReason.reason_id,
            froms: Platform.OS === 'ios' ? 'IOS' : 'Android',
            action_desc: this.descText,
            goods: goodsData,
            resion_img: state.userGoodsImage,
        };
        this.iparNetwork.getPostJson(SERVER_TYPE.adminIpar + 'applyReturn', data)
            .then((result) => {
                CommonUtils.dismissLoading();
                console.log(result);
                if (result.code === 200) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'));
                    this.props.navigator.push({
                        component: ReturnOrdersPage,
                        name: 'ReturnOrdersPage',
                        params: {
                            ...this.props,
                        }
                    })
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }
            })
            .catch((error) => {
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('ReturnGoodsPage---getReasonData--error:' + error);
                CommonUtils.dismissLoading();
            });
    }


}

const styles = StyleSheet.create({
    box: {
        backgroundColor: 'white'
    },
    iconBox: {
        width: 26,
        height: 26,
    },
    iconSize: {
        width: 16,
        height: 16,
    },

    goodsTitle: {
        fontSize: 18,
        padding: 16,
        color: 'gray'
    },

    text: {
        fontSize: 16,
    }
});

